package com.thd.springboottest.camunda.controller;

import com.thd.springboottest.camunda.dto.ProcDefEntity;
import com.thd.springboottest.camunda.dto.ProcessInstanceEntity;
import com.thd.springboottest.camunda.dto.ProcessInstanceTaskEntity;
import com.thd.springboottest.camunda.service.WorkFlowService;
import org.camunda.bpm.engine.ProcessEngine;
import org.camunda.bpm.engine.repository.ProcessDefinition;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/camunda/example")
public class Camunda00example {



    @Autowired
    private ProcessEngine processEngine;
    @Autowired
    private WorkFlowService workFlowService;


    @RequestMapping("/deploy")
    // url : http://127.0.0.1:8899/thd/camunda/example/deploy
    public ResponseEntity<String> deploy(){
        String deployId = this.workFlowService.deploy("processes/00example.bpmn");
        System.out.println("deployId:"+deployId);
        return ResponseEntity.ok("SUCCESS");
    }

    @RequestMapping("/queryProcessDef")
    // url : http://127.0.0.1:8899/thd/camunda/example/queryProcessDef
    public ResponseEntity<List<ProcDefEntity>> queryProcessDef(){
        List<ProcessDefinition> processDefinitionList = this.processEngine.getRepositoryService().createProcessDefinitionQuery().list();
        List<ProcDefEntity> r = processDefinitionList.stream().map( pd -> {
            ProcDefEntity procDefEntity = new ProcDefEntity();
            procDefEntity.setDefName(pd.getName());
            procDefEntity.setProcDefId(pd.getId());
            procDefEntity.setDefVersion(String.valueOf(pd.getVersion()));
            procDefEntity.setDefKey(pd.getKey());
            return procDefEntity;
        }).collect(Collectors.toList());
        return ResponseEntity.ok(r);
    }


    @RequestMapping("/start")
    // url : http://127.0.0.1:8899/thd/camunda/example/start
    public ResponseEntity<ProcessInstanceEntity> start(){
        String businessKey = UUID.randomUUID().toString();
        Map<String,Object> procVar = new HashMap<String,Object>();
        procVar.put("assignee","zhangsan");
        procVar.put("manager","lisi");
        procVar.put("boss","wangwu");
        ProcessInstance pi = processEngine.getRuntimeService().startProcessInstanceByKey("ApplicationForLeave",businessKey,procVar);
        System.out.println(String.format("process instance id:%s",pi.getProcessInstanceId()));

        ProcessInstanceEntity procInst = new ProcessInstanceEntity();
        procInst.setBusinessKey(pi.getBusinessKey());
        procInst.setProcessInstanceId(pi.getProcessInstanceId());
        return ResponseEntity.ok(procInst);
    }


    @RequestMapping("/queryProcessInstanceByProcessInstanceId/{processInstanceId}")
    // url : http://127.0.0.1:8899/thd/camunda/example/queryProcessInstanceByProcessInstanceId/xxx
    public ResponseEntity<ProcessInstanceEntity> queryProcessInstanceByProcessInstanceId(@PathVariable String processInstanceId){
        // 根据id查询流程实例
        ProcessInstance pi = processEngine.getRuntimeService().createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        // 根据key查询流程实例
        if(null == pi){
            pi = processEngine.getRuntimeService().createProcessInstanceQuery().processInstanceBusinessKey(processInstanceId).singleResult();
        }

        ProcessInstanceEntity procInst = new ProcessInstanceEntity();

        procInst.setProcessInstanceId(pi.getProcessInstanceId());
        procInst.setBusinessKey(pi.getBusinessKey());
        return ResponseEntity.ok(procInst);
    }



    @RequestMapping("/queryTaskByBusinessKey/{businessKey}")
    // url : http://127.0.0.1:8899/thd/camunda/example/queryTaskByBusinessKey/xxx
    public ResponseEntity<List<ProcessInstanceTaskEntity>> queryTaskByBusinessKey(@PathVariable String businessKey){
        List<ProcessInstanceTaskEntity> taskList = workFlowService.queryTaskByBusinessKey(businessKey);

        List<ProcessInstanceTaskEntity> r =
        taskList.stream().map( task -> {

            ProcessInstanceTaskEntity taskEntity = new ProcessInstanceTaskEntity();

            taskEntity.setTaskId(task.getTaskId());
            taskEntity.setTaskDefKey(task.getTaskDefKey());
            taskEntity.setTaskName(task.getTaskName());
            taskEntity.setTaskAssignee(task.getTaskAssignee());
            return taskEntity;
        }).collect(Collectors.toList());
        return ResponseEntity.ok(r);
    }

    @RequestMapping("/queryTaskByTaskId/{taskId}")
    // url : http://127.0.0.1:8899/thd/camunda/example/queryTaskByTaskId/xxx
    public ResponseEntity<ProcessInstanceTaskEntity> queryTaskByTaskId(@PathVariable String taskId){
        ProcessInstanceTaskEntity task = workFlowService.queryTaskByTaskId(taskId);
        return ResponseEntity.ok(task);
    }

    @RequestMapping("/queryTaskByUser/{userName}")
    // url : http://127.0.0.1:8899/thd/camunda/example/queryTaskByUser/userName
    public ResponseEntity<List<ProcessInstanceTaskEntity>> queryTaskByUser(@PathVariable String userName){
        List<ProcessInstanceTaskEntity> taskList = workFlowService.queryTaskForUser(userName);
//        taskList.forEach( task -> {
//            System.out.println("=====================");
//            System.out.println(String.format("task name:%s",task.getTaskName()));
//            System.out.println(String.format("task def name:%s",task.getTaskDefKey()));
//            System.out.println(String.format("task id:%s",task.getTaskId()));
//        });
        return ResponseEntity.ok(taskList);
    }


    @RequestMapping("/submitApply/{taskId}")
    // url : http://127.0.0.1:8899/thd/camunda/example/submitApply/xxx
    public ResponseEntity<String> submitApply(@PathVariable String taskId){
        ProcessInstanceTaskEntity task = workFlowService.queryTaskByTaskId(taskId);
        Map<String ,Object> procVar = new HashMap<String,Object>();
        procVar.put("days",3);
        procVar.put("manager","lisi");
        workFlowService.completeTask(taskId,procVar);
        return ResponseEntity.ok("SUCCESS");
    }

    @RequestMapping("/submitManagerApprove/{taskId}")
    // url : http://127.0.0.1:8899/thd/camunda/example/submitManagerApprove/xxx
    public ResponseEntity<String> submitManagerApprove(@PathVariable String taskId){
        ProcessInstanceTaskEntity task = workFlowService.queryTaskByTaskId(taskId);
        Map<String ,Object> procVar = new HashMap<String,Object>();
        procVar.put("status","PASS");
        procVar.put("boss","wangwu");
        workFlowService.completeTask(taskId,procVar);
        return ResponseEntity.ok("SUCCESS");
    }


    @RequestMapping("/submitBossApprove/{taskId}")
    // url : http://127.0.0.1:8899/thd/camunda/example/submitBossApprove/xxx
    public ResponseEntity<String> submitBossApprove(@PathVariable String taskId){
        ProcessInstanceTaskEntity task = workFlowService.queryTaskByTaskId(taskId);
        workFlowService.completeTask(taskId,null);
        return ResponseEntity.ok("SUCCESS");
    }


    @RequestMapping("/jump/{processInstanceId}/{activitiId}")
    // url : http://127.0.0.1:8899/thd/camunda/example/jump/xxx
    public ResponseEntity<String> jump(@PathVariable String processInstanceId,@PathVariable String activitiId){
        workFlowService.jump(processInstanceId,activitiId);
        return ResponseEntity.ok("SUCCESS");
    }





}
